package class3;

import common.ListNode;
import common.ListNodeUtils;

/**
 * https://leetcode.cn/problems/7WHec2/description/
 * https://leetcode.cn/problems/sort-list/description/
 * 链表排序
 * 解题思路：
 * 1.链表归并排序
 */
public class Code25_LinkedSort {
    public static void main(String[] args) {
        ListNode head = ListNodeUtils.getLinked(3, 5, 6, 4, 5, 2, 6, 9, 0, 1);


        // 排序链表
        ListNode sortedList = sortList(head);
        ListNodeUtils.print(sortedList);
    }

    public static ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode mid = getMid(head);// 获取中间
        ListNode left = head, right = mid.next;
        mid.next = null; // 断开链表
        left = sortList(left);
        right = sortList(right);
        return merge(left, right);
    }

    public static ListNode merge(ListNode left, ListNode right) {
        ListNode d = new ListNode(0);
        ListNode cur = d;
        while (left != null && right != null) {
            // 将小的节点放到cur后
            if (left.val > right.val) {
                cur.next = right;
                right = right.next;
            } else {
                cur.next = left;
                left = left.next;
            }
            cur = cur.next;
        }
        if (left != null) {
            cur.next = left;
        }
        if (right != null) {
            cur.next = right;
        }
        return d.next;
    }

    public static ListNode getMid(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}
